<?php
namespace app\api\controller;
use think\Db;
use app\admin\model\Orders;
class Order extends Common {
	private $token;
	private $rush_order_id;
	private $userinfo;

	private $ak = 'xnZHVFG7IwuFQMgHkcbIGFDx07MZnQl8';
	private $db = null;
	private $config = '';
	private $oto_db_prefix = ''; //oto平台数据库名和表前缀
	private $pt_table_prefix = ''; //跑腿平台表前缀
	private $orderField = '';
	protected function _initialize(){
		parent::_initialize();
		$this->config = config('database.db_config');
		$this->oto_db_prefix = $this->config['database'].'.'.$this->config['prefix'];
		$this->pt_table_prefix = config('database.prefix');
		$this->db = Db::connect($this->config);
	}


	// 待抢单
	public function rush_order(){
		$this->is_validate();
		$this->f_iscancel();
		$arrShop = array();
		$model = db('user');
		$model_orders = db('delivery_order');
		$oto_model = $this->db->name('orders');
		$page = $this->request->post('page');
		$userId = $this->userinfo['id'];
		$user_range = $model->where('id',$userId)->value('delivery_id');

		// 符合配送范围的商家
		$shops = db('set_section')->field('shopId,section')->select();
		$shopId_arr = array();

		foreach ($shops as $shop) {
			$shop_range = $shop['section'];
			$shop_range = explode(",", $shop_range);

			foreach ($shop_range as $range) {
				if(strpos($user_range, $range) !== false ){
					$shopId_arr[]=$shop['shopId'];
					break;
				}
			}
			unset($range);
		}
		unset($shop);

		$num = array();

		// $num[0] = $oto_model->where('shopId','in',$shopId_arr)->where(array('orderStatus'=>1,'deliverType'=>1))->where('isRefund','not in','1,2,3')->count();
		// 唐峰康改 没有店铺id的
		// $num[0] = db('send_order')->where(array('order_status'=>0,'pay_status'=>1))->count();
			
		$num[1] = $model_orders->where(array("userId"=>$userId,'status'=>0,'iscancel'=>0))->count();
		$num[2] = $model_orders->where(array("userId"=>$userId,'status'=>1,'iscancel'=>0))->count();
		$num[3] = $model_orders->where(array("userId"=>$userId,'iscancel'=>0))->where('status','in','2,3')->count();
		$num[4] = $model_orders->where(array("userId"=>$userId,'iscancel'=>1))->count();

		// 相应订单状态（已接单or打包中）的订单数据
		// $oto_orders = $oto_model->where('shopId','in',$shopId_arr)->where(array('orderStatus'=>1,'deliverType'=>1))->where('isRefund','not in','1,2,3')->order('paytime DESC')->select(); //->limit((10 * $page) . ",10")
		// $oto_orders =  db('send_order')->where(array('order_status'=>0,'pay_status'=>1))->select(); //->limit((10 * $page) . ",10")
		// echo count($oto_orders);
		// p($oto_orders);
		// exit();
		// foreach ($oto_orders as $oto_order) {
		// 	// 订单id
		// 	$orderId = $oto_order['orderId'];

		// 	// 对应订单状态的商家id的商家
		// 	$oto_shop = $this->db->name('shops')->where(array('shopId'=>$oto_order['shopId']))->find();
		// 	// if (!empty($oto_shop)) {
		// 	// 	continue;
		// 	// }

		// 	// 商家店铺id
		// 	$shopId = $oto_shop['shopId'];
		// 	$orderStatus = $oto_order['orderStatus'];

		// 	// 商家店铺名
		// 	$shopName = $oto_shop['shopName'];

		// 	// 商家地址
		// 	$shopAddress = $oto_shop['shopAddress'];

		// 	// 商家纬度
		// 	$shopLatitude = $oto_shop['latitude'];

		// 	// 商家经度
		// 	$shopLongitude = $oto_shop['longitude'];
		// 	// 商家经纬度
		// 	$shopLngLat = $shopLongitude.','.$shopLatitude;

		// 	// 买家地址
		// 	$buyerAddress = $oto_order['userAddress'];

		// 	// 买家纬度
		// 	$buyerLatitude = $oto_order['lat'];
		// 	// 买家经度
		// 	$buyerLongitude = $oto_order['lng'];
		// 	// 买家经纬度
		// 	if ($buyerLatitude == null || $buyerLatitude == '' || $buyerLongitude == null || $buyerLongitude == '') {
		// 		$buyerLngLat = '';
		// 	}else{
		// 		$buyerLngLat = $buyerLongitude.','.$buyerLatitude;
		// 	}
		// 	// $buyerLngLat = $buyerLongitude.','.$buyerLatitude;

		// 	// 商家到买家的距离
		// 	$shop_to_buyer = getDistance($shopLatitude,$shopLongitude,$buyerLatitude,$buyerLongitude);

		// 	// 配送费
		// 	$deliverMoney = number_format($oto_order['deliverMoney'],2,'.','');

		// 	$arrShop[] = array('order_type' => 'default',"orderId"=>$orderId,"shopId"=>$shopId,"shopName"=>$shopName,"shopAddress"=>$shopAddress,"shopLngLat"=>$shopLngLat,"buyerLngLat"=>$buyerLngLat,"buyerAddress"=>$buyerAddress,"shop_to_buyer"=>$shop_to_buyer,"deliverMoney"=>$deliverMoney,"orderStatus"=>$orderStatus);
			
		// }
		// 唐峰康改 获取待抢单目的地和配送员的距离范围
		$distanceInfo = $this->db->name('sys_configs')->where(array('fieldCode'=>'showdistance'))->find();
		$show_distance = $distanceInfo['fieldValue'];

		$lng = $this->request->post('u_lng');
		$lat = $this->request->post('u_lat');
		// 配送员到 取货目的地 的距离
// 		$startLng = round($lng,3);
// 		$endLng = sprintf("%.3f",substr(sprintf("%.5f", $lng), 0, -2));
		
// 		$startLat = round($lat,2);
// 		$endLat = sprintf("%.4f",substr(sprintf("%.6f", $lat), 0, -2));
		//$where = "(lng<'{$startLng}' and lng>'{$endLng}') and (lat<'{$startLat}' and lat>'{$endLat}')";
		// $where = "pay_status=1 and order_status=0 and user_lng >='{$lng}' and user_lat >='{$lat}'";
		$where = "pay_status=1 and order_status=0";
		$data = db('send_order')->where($where)->select();
		// ajaxReturn(array('status' => 'success','num'=>$num,'lng'=>$lng,'lat'=>$lat,'data' => $delivery_to_shop));
		$user_delivery_config = db('system')->where(array('name' => 'delivery_user_config'))->find();
		$user_delivery_config = unserialize($user_delivery_config['value']);
		$temp = array();
		foreach ($data as $key => $value){
			$value['content'] = json_decode($value['content'],true);
			$value['order_type'] = 'user_send';
			$diff = time()-$value['time'];
			if ($diff >= 3600*24){
				$value['downtime'] = date('Y-m-d H:i:s',$value['time']);
			}elseif ($diff >= 3600){
				$value['downtime'] = date('H时i分s秒',$diff);
			}else{
				$value['downtime'] = date('i分s秒',$diff);
			}
			
			if ($value['type'] == 3){
				$value['my_location'] = subMoney(getDistance($lat, $lng, $value['content']['buy_lat'], $value['content']['buy_lng']));
				$value['to_location'] = subMoney(getDistance($value['content']['buy_lat'], $value['content']['buy_lng'], $value['content']['get_lat'], $value['content']['get_lng']));
			}else{
				$value['my_location'] = subMoney(getDistance($lat, $lng, $value['content']['go_lat'], $value['content']['go_lng']));
				// 超过显示范围 唐峰康改
				if (getDistance($lat, $lng, $value['content']['go_lat'], $value['content']['go_lng'])>$show_distance) {
					continue;
				}
				$value['to_location'] = subMoney(getDistance($value['content']['go_lat'], $value['content']['go_lng'], $value['content']['get_lat'], $value['content']['get_lng']));
			}
			
			foreach ($user_delivery_config as $k => $j){
				if ($j['go_distance'] >= $value['to_location']){
					switch ($value['content']['car']){
						case 1:
							$value['money'] = number_format(floatval($j['go_shop_money']),2);
							break;
						case 2:
							$value['money'] = $j['go_shop_money2'];
							break;
						case 3:
							$value['money'] = $j['go_shop_money2'];
							break;
					}
					break;
				}
			}
			
			switch ($value['content']['car']){
				case 1:
					$value['content']['car_text'] = '摩托车(电动车)';
					break;
				case 2:
					$value['content']['car_text'] = '小汽车';
					break;
				case 3:
					$value['content']['car_text'] = '火车';
					break;
			}
			switch ($value['content']['type']){
				case 1:
					$value['content']['type_text'] = '帮我送';
					break;
				case 2:
					$value['content']['type_text'] = '帮我取';
					break;
				case 3:
					$value['content']['type_text'] = '帮我买';
					break;
				case 4:
					$value['content']['type_text'] = '饿了么订单';
					break;
			}
			$temp[] = $value;
		}
		// $num[0] = count($temp)+$num[0];
		// 唐峰康改 排除不在返回之后的数量
		$num[0] = count($temp);
		$arrShop = array_merge($arrShop,$temp);
		//p($arrShop);
		ajaxReturn(array('status' => 'success','num'=>$num,'data' => $arrShop));
	}
	
	// 待取货，配送中，已到达，已完成，已取消
	public function get_lists(){
		$this->is_validate();
		$this->f_iscancel();
		$arrShop = array();
		$model = db('delivery_order');
		$updata_status = $this->request->post('status');
		$page = $this->request->post('page');
		$userId = $this->userinfo['id'];
		$lng = $this->request->post('u_lng');
		$lat = $this->request->post('u_lat');
		
		$where = "pay_status=1 and order_status=0 and (user_lng>='{$lng}' and user_lat>='{$lat}')";
		$send_data = db('send_order')->where($where)->order('id desc')->select();
		
		$user_range = db('user')->where('id',$userId)->value('delivery_id');
		// 符合配送范围的商家
		$shops = db('set_section')->field('shopId,section')->select();
		$shopId_arr = array();
		foreach ($shops as $shop) {
			$shop_range = $shop['section'];
			$shop_range = explode(",", $shop_range);

			foreach ($shop_range as $range) {
				if(strpos($user_range, $range) !== false ){
					$shopId_arr[]=$shop['shopId'];
					break;
				}
			}
			unset($range);
		}
		unset($shop);
		$num = array();
		// $num[0] = $this->db->name('orders')->where('shopId','in',$shopId_arr)->where(array('orderStatus'=>1,'deliverType'=>1))->where('isRefund','not in','1,2,3')->count();
		// $num[0] = count($send_data)+$num[0];

		// 唐峰康改 获取待抢单目的地和配送员的距离范围
		$distanceInfo = $this->db->name('sys_configs')->where(array('fieldCode'=>'showdistance'))->find();
		$show_distance = $distanceInfo['fieldValue'];
		$rush_order_num = 0;

		$where = "pay_status=1 and order_status=0";
		$send_order_data = db('send_order')->where($where)->select();
		foreach ($send_order_data as $key => $value) {
			$value['content'] = json_decode($value['content'],true);
			// 超过显示范围 唐峰康改
			if (getDistance($lat, $lng, $value['content']['go_lat'], $value['content']['go_lng'])>$show_distance) {
				continue;
			}
			$rush_order_num++;
		}
		$num[0] = $rush_order_num;
		$user = db('user')->where(array('id'=>$userId,'check_status'=>1))->where('delivery_id','not in','0,null')->find();
		if (!empty($user)) {
			$num[1] = $model->where(array("userId"=>$userId,'status'=>0,'iscancel'=>0))->count();
			$num[2] = $model->where(array("userId"=>$userId,'status'=>1,'iscancel'=>0))->count();
			$num[3] = $model->where(array("userId"=>$userId,'iscancel'=>0))->where('status','in','2,3')->count();
			$num[4] = $model->where(array("userId"=>$userId,'iscancel'=>1))->count();
		}else{
			$num[1] = '';
			$num[2] = '';
			$num[3] = '';
			$num[4] = '';
		}
		// 获取相应订单状态（已接单or打包中）的订单数据
		
		if ($updata_status == '0') {
			$orders = $model->where(array("userId"=>$userId,'status'=>0,'iscancel'=>0))->limit((10 * $page) . ",10")->order('id desc')->select();
		}elseif ($updata_status == '1') {
			$orders = $model->where(array("userId"=>$userId,'status'=>1,'iscancel'=>0))->limit((10 * $page) . ",10")->order('id desc')->select();
		}elseif ($updata_status == '2') {
			$orders = $model->where(array("userId"=>$userId,'iscancel'=>0))->where('status','in','2,3')->order('id DESC')->limit((10 * $page) . ",10")->order('id desc')->select();
		}elseif ($updata_status == '3') {
			$orders = $model->where(array("userId"=>$userId,'iscancel'=>1))->order('id DESC')->limit((10 * $page) . ",10")->order('id desc')->select();
		}
		
		$user_delivery_config = db('system')->where(array('name' => 'delivery_user_config'))->find();
		$user_delivery_config = unserialize($user_delivery_config['value']);
		
		$delivery_config = db('system')->where(array('name' => 'delivery_config'))->find();
		$delivery_config = unserialize($delivery_config['value']);
		
		// p($orders);
		// exit();
		$temp_x = array();
		foreach ($orders as $order) {
			if ($order['user_send'] == 1){
				$user_sendOrder = db('send_order')->where(array('id' => $order['orderId']))->find();
				$user_sendOrder['content'] = json_decode($user_sendOrder['content'],true);
				switch ($user_sendOrder['content']['car']){
					case 1:
						$user_sendOrder['content']['car_text'] = '摩托车(电动车)';
						break;
					case 2:
						$user_sendOrder['content']['car_text'] = '小汽车';
						break;
					case 3:
						$user_sendOrder['content']['car_text'] = '火车';
						break;
				}
				switch ($user_sendOrder['content']['type']){
					case 1:
						$user_sendOrder['content']['type_text'] = '帮我送';
						break;
					case 2:
						$user_sendOrder['content']['type_text'] = '帮我取';
						break;
					case 3:
						$user_sendOrder['content']['type_text'] = '帮我买';
						break;
					case 4:
					$user_sendOrder['content']['type_text'] = '饿了么订单';
					break;
				}
				//$user_sendOrder['content']['money'] = $user_sendOrder['money'];
				$user_sendOrder['content']['pay_status'] = $user_sendOrder['pay_status'];
				$user_sendOrder['content']['order_status'] = $user_sendOrder['order_status'];
				$user_sendOrder['content']['user_lng'] = $user_sendOrder['user_lng'];
				$user_sendOrder['content']['user_lat'] = $user_sendOrder['user_lat'];
				$order['content'] = $user_sendOrder['content'];
				$order['order_type'] = 'user_send';
				if ($user_sendOrder['type'] == 3){
					$order['my_location'] = subMoney(getDistance($lat, $lng, $user_sendOrder['content']['buy_lat'], $user_sendOrder['content']['buy_lng']));
					$order['to_location'] = subMoney(getDistance($user_sendOrder['content']['buy_lat'], $user_sendOrder['content']['buy_lng'], $user_sendOrder['content']['get_lat'], $user_sendOrder['content']['get_lng']));
				}else{
					$order['my_location'] = subMoney(getDistance($lat, $lng, $user_sendOrder['content']['go_lat'], $user_sendOrder['content']['go_lng']));
					$order['to_location'] = subMoney(getDistance($user_sendOrder['content']['go_lat'], $user_sendOrder['content']['go_lng'], $user_sendOrder['content']['get_lat'], $user_sendOrder['content']['get_lng']));
				}
				foreach ($user_delivery_config as $k => $j){
					if ($j['go_distance'] >= $order['to_location']){
						switch ($user_sendOrder['content']['car']){
							case 1:
								$user_sendOrder['content']['money'] = $j['go_shop_money'];
								break;
							case 2:
								$user_sendOrder['content']['money'] = $j['go_shop_money2'];
								break;
							case 3:
								$user_sendOrder['content']['money'] = $j['go_shop_money2'];
								break;
						}
						break;
					}
				}
				if ($user_sendOrder['content']['urgent'] == 2){
					$user_sendOrder['content']['money'] += $user_sendOrder['content']['money']*(float)(get_system_info('user_urgent'))/100;
				}
				
				if ($order['deliverMoney'] <= 0){
					$model->where(['id' => $order['id']])->setField('deliverMoney',$user_sendOrder['content']['money']);
				}
				
				//用户发布时间
				$createTime = $user_sendOrder['time'];
				//要求送达时间
				// $requireTime = strtotime($user_sendOrder['send_time']);
				// 唐峰康改 要求送达时间 = 接单时的时间+后台设置的送达时间 接单的时候delivery_order存有
				$requireTime =$order['require_time'];
				$countdown = array();
				if ($requireTime>=time()) {
					$countdown["status"] = 1;	//没有超时
					$countdown['time'] = intval(($requireTime - time())/60).'分钟';
				}else{
					$countdown["status"] = 0;	//超时
					// $stime = _put_time($user_sendOrder['send_time']);

					$stime = _put_time($requireTime);
					$stime = mb_substr($stime, 0,-1,'utf-8');
					$countdown['time'] = $stime;
				}
				//送达时间 接单的时候delivery_order 的 require_time 要求送达时间
				// $sendToTime = date('Y-m-d H:i:s',$user_sendOrder['send_time']);
				$sendToTime = date('Y-m-d H:i:s',$requireTime);
				//用户确认收货
				$confirmTime = '';
				$isConfirm = '未确认';
				if ($order['status'] == 3) {
					if ($order['confirm_time'] != 0) {
						$isConfirm = date('Y-m-d H:i:s',$order['confirm_time']);
					}
					//确认时间
					//$confirmTime = strtotime($order['confirm_time']);
				}
				$order['sendToTime'] = $sendToTime;
				$order['isConfirm'] = $isConfirm;
				$order['countdown'] = $countdown;
				//$order['deliverMoney'] = $user_sendOrder['content']['money'];
				$order['orderRemarks'] = $user_sendOrder['content']['remark'];
				$temp_x[] = $order;
			}else{
				// 订单id
				$orderId = $order['orderId'];
	
				// 订单状态
				$status = $order['status'];
	
				// 商家店铺id
				$shopId = $order['shopId'];
	
				// 商家经纬度
				$shopLngLat = $order['shopLngLat'];
				$shopLngLatArr = explode(",", $shopLngLat);
	
				// 买家经纬度
				$buyerLngLat = $order['buyerLngLat'];
				$buyerLngLatArr = explode(",", $buyerLngLat);
	
				$shopLongitude = isset($shopLngLatArr[0]) ? $shopLngLatArr[0] : '';
				$shopLatitude = isset($shopLngLatArr[1]) ? $shopLngLatArr[1] : '';
				$buyerLongitude = isset($buyerLngLatArr[0]) ? $buyerLngLatArr[0] : '';
				$buyerLatitude = isset($buyerLngLatArr[1]) ? $buyerLngLatArr[1] : '';
	
				// 对应订单状态的商家id的商家
				$oto_shop = $this->db->name('shops')->where('shopId',$shopId)->find();
				$oto_order =  $this->db->name('orders')->where('orderId',$orderId)->find();
	
				if (empty($shopLongitude)) {
					$shopLongitude = $oto_shop['longitude'];
					$shopLngLat = $oto_shop['longitude'].','.$oto_shop['latitude'];
				}
				if (empty($shopLatitude)) {
					$shopLatitude = $oto_shop['latitude'];
				}
				if (empty($buyerLongitude)) {
					$buyerLongitude = $oto_order['lng'];
					$buyerLngLat = $oto_order['lng'].','.$oto_order['lat'];
					$model->where(['id' => $order['id'],'user_send' => 0])->update([
							'shopLngLat' => $shopLngLat,
							'buyerLngLat' => $buyerLngLat
					]);
				}
				if (empty($buyerLatitude)) {
					$buyerLatitude = $oto_order['lat'];
				}
				
				// 判断订单是否取消
				$oto_isRefund = $oto_order['isRefund'];
				$iscost = '';
				if ($oto_isRefund == 1 || $oto_isRefund == 2 || $oto_isRefund == 3) {
					if ($updata_status == 3) {
						if ($status == 1 || $status == 2 || $status == 3) {
							$iscost = 1;
						}else {
							$iscost = 0;
						}
					}
					$model->where(['orderId' => $orderId,'user_send' => 0])->setField('iscancel','1');
				}
	
				// 商家店铺名
				$shopName = $oto_shop['shopName'];
	
				// 商家地址
				$shopAddress = $oto_shop['shopAddress'];
	
				// 买家地址
				$buyerAddress = $oto_order['userAddress'];
	
				// 商家到买家的距离
				$shop_to_buyer = getDistance($shopLatitude,$shopLongitude,$buyerLatitude,$buyerLongitude);

				// 配送费
				$iscount = $order['iscount'];
				// $deliverMoney = number_format($oto_order['deliverMoney'],2,'.','');
				foreach ($delivery_config as $k => $j){
					if ($j['go_distance'] >= $shop_to_buyer){
						switch ($oto_order['car']){
							case 1:
								$deliverMoney = $j['go_shop_money'];
								break;
							case 2:
								$deliverMoney = $j['go_shop_money2'];
								break;
							case 3:
								$deliverMoney = $j['go_shop_money2'];
								break;
						}
						break;
					}
				}
				
				if ($oto_order['urgent'] == 2){
					$deliverMoney += $deliverMoney*(float)(get_system_info('user_urgent'))/100;
				}
				if ($order['deliverMoney'] <= 0){
					$model->where(['id' => $order['id']])->setField('deliverMoney',$deliverMoney);
				}
				// 买家留言
				if ($oto_order['orderRemarks']) {
					$orderRemarks = $oto_order['orderRemarks'];
				}else{
					$orderRemarks = '无';
				}
				// 接单时间（时间戳）
				$time = $order['time'];
				// 买家下单时间
				$createTime = strtotime($oto_order['createTime']);
				// 要求送达时间
				$requireTime = $order['require_time'];
				$countdown = array();
				if ($requireTime>=time()) {
					$countdown["status"] = 1;	//没有超时
				}else{
					$countdown["status"] = 0;	//超时
				}
				$countdown["time"] = round(abs($requireTime - time())/60);
				// 送达时间
				$sendToTime = date('Y-m-d H:i:s',$order['send_to_time']);
				// 用户确认收货
				if ($oto_order['isConfirm'] == '1') {
					if ($oto_order['signTime'] !== false && $oto_order['signTime'] != null) {
						$isConfirm = $oto_order['signTime'];
					}else{
						$isConfirm = '无';
					}
					//确认时间
					$confirmTime = strtotime($oto_order['signTime']);
					$model->where('orderId',$orderId)->update(['confirm_time'=>$confirmTime]);
				}else{
					$isConfirm = '未确认';
				}
				
				$arrShop[] = array('order_type' => 'default','id' => $order['id'],"orderId"=>$orderId,"status"=>$status,"shopId"=>$shopId,"shopName"=>$shopName,"shopAddress"=>$shopAddress,"shopLngLat"=>$shopLngLat,"buyerLngLat"=>$buyerLngLat,"buyerAddress"=>$buyerAddress,"shop_to_buyer"=>$shop_to_buyer,"iscount"=>$iscount,"deliverMoney"=>$deliverMoney,"countdown"=>$countdown,"orderRemarks"=>$orderRemarks,"sendToTime"=>$sendToTime,"isConfirm"=>$isConfirm,'iscost'=>$iscost);
			
			}
		}
		//p($arrShop);
		$arrShop = array_merge($arrShop,$temp_x);
		ajaxReturn(array('status' => 'success','num'=>$num,'data' => $arrShop));
	}

	private function is_validate(){
		if (!request()->isPost()) ajaxReturn(array('status' => 'error','msg' => '网络错误'));
		$token = $this->request->param('token');
		if ($token != config('token')) ajaxReturn(array('status' => 'error','msg' => '网络错误'));
		$user_id = $this->request->post('userId');
		$user_id = _encrypt($user_id,'DECODE');
		$userinfo = db('user')->where(array('id'=>$user_id,'check_status'=>1))->find();
		if (empty($userinfo)) {
			ajaxReturn(array('status' => 'error','msg' => '您未认证，请先认证。'));
		}
		// $delivery_id = db('user')->where(array('id'=>$user_id,'check_status'=>1))->value('delivery_id');
		// if ($delivery_id == "" || $delivery_id == 0 || $delivery_id ==null || !$delivery_id) {
		// 	ajaxReturn(array('status' => 'delivery','msg' => '没有配送范围，请与工作人员联系'));
		// }
		$this->token = $token;
		$this->userinfo = $userinfo;
	}
		
	private function post_check(){
		if (!request()->isPost()) ajaxReturn(array('status' => 'error','msg' => '网络错误'));
		$token = $this->request->param('token');
		$rush_order_id = $this->request->post('orderId');
		if ($token != config('token')) ajaxReturn(array('status' => 'error','msg' => '网络错误'));

		$this->token = $token;
		$this->rush_order_id = $rush_order_id;
	}
	// 判断订单是否取消，用户是否确认
	private function f_iscancel(){
		$user_id = $this->request->post('userId');
		$user_id = _encrypt($user_id,'DECODE');
		$model = db('delivery_order');
		$oto_order = $this->db->name('orders');
		$orders = $model->where(array('userId'=>$user_id,'iscancel'=>0))->where('status','in','0,1,2')->select();
		foreach ($orders as $order) {
			$orderId = $order['orderId'];
			$oto_isRefund = $oto_order->where('orderId',$orderId)->where('isRefund','in','1,2,3')->find();
			if (!empty($oto_isRefund)) {
				$model->where('orderId',$orderId)->setfield('iscancel',1);
			}
			$oto_isConfirm = $oto_order->where('orderId',$orderId)->where('isConfirm','1')->find();
			if (!empty($oto_isConfirm)) {
				$model->where('orderId',$orderId)->setfield('status',3);
			}
		}
	}
	// 抢单成功，订单列表写入数据库
	public function delivery_order(){
		$this->post_check();
		$this->is_validate();
		$userId = $this->userinfo['id'];
		// $userId = 14;
		// 判断是否开启接单
		$is_job = db('user')->where(array('id'=>$userId,'is_job'=>1))->find();
		if (empty($is_job)){
			ajaxReturn(array('status' => '3','msg' => '请在个人中心开启接单'));
		}
		// 判断配送员接单量是否已打上限
		// 1.当前接单量 -需求，总的
		// $current_order_num = db('delivery_order')->where(array('userId'=>$userId))->count();
		// 1-1 需求更改 待取货~待配送的
		$current_order_num = db('delivery_order')->where("userId='{$userId}' and status <= 1 and iscancel = 0")->count();
		// 2.平台设置的接单量
		$max_order_num = $this->db->name('sys_configs')->where(array('fieldCode'=>'deliveryOrderNum'))->value('fieldValue');
		if (is_numeric($max_order_num) && $max_order_num>0 && $max_order_num<=$current_order_num) {
			ajaxReturn(array('status' => '3','msg' => '已接单未完成的数量已经超过上限'));
		}
		// 订单id
		$orderId = $this->rush_order_id;
		$order_type = $this->request->post('order_type');
		// 配送员经纬度
		$diliveryman_lng = $this->request->post('lng');
		$diliveryman_lat = $this->request->post('lat');
		$diliverymanLngLat = $diliveryman_lng.','.$diliveryman_lat;
		//$orderId = 1;
		
		if ($order_type == 'default'){
			// 查找对应订单id的订单
			$oto_order = $this->db->name('orders')->where('orderId',$orderId)->find();
			// 判断订单是否取消
			$oto_isRefund = $oto_order['isRefund'];
			if ($oto_isRefund == '1' || $oto_isRefund == '2' || $oto_isRefund == '3') {
				ajaxReturn(array('status' => '1','msg' => '该订单已取消'));
			}

			// 商家id
			$shopId = $oto_order['shopId'];

			// 查找对应商家id的商家
			$oto_shop = $this->db->name('shops')->where('shopId',$shopId)->find();

			// 商家经度
			$shopLatitude = $oto_shop['latitude'];
			// 商家纬度
			$shopLongitude = $oto_shop['longitude'];
			// 商家经纬度
			if ($shopLatitude == null || $shopLatitude == '' || $shopLongitude == null || $shopLongitude == '') {
				$shopLngLat = '';
			}else{
				$shopLngLat = $shopLongitude.','.$shopLatitude;
			}

			// 买家地址
			// $buyerAddress = $oto_order['userAddress'];

			// 买家经度
			$buyerLatitude = $oto_order['lat'];
			// 买家纬度
			$buyerLongitude = $oto_order['lng'];
			// 买家经纬度
			if ($buyerLatitude == null || $buyerLatitude == '' || $buyerLongitude == null || $buyerLongitude == '') {
				$buyerLngLat = '';
			}else{
				$buyerLngLat = $buyerLongitude.','.$buyerLatitude;
			}
			
			// 商家到买家的距离
			$shop_to_buyer = getDistance($shopLatitude,$shopLongitude,$buyerLatitude,$buyerLongitude);

			// 配送费
			$deliverMoney = number_format($oto_order['deliverMoney'],2,'.','');

			// 订单状态
			$status = '0';

			// 接单时间
			$time = time();
			$delivery_config = delivery_config($shop_to_buyer);
			$requireTime = $time + $delivery_config['go_distance_time']*60;

			$data = ["userId"=>$userId,"orderId"=>$orderId,"shopId"=>$shopId,"shopLngLat"=>$shopLngLat,"buyerLngLat"=>$buyerLngLat,"status"=>$status,"require_time"=>$requireTime,"deliverMoney"=>$deliverMoney,"time"=>$time];
			
			// 导入数据库
			db('delivery_order')->insert($data);
			// 改订单状态
			$requireTimeStr = date('H:i',$requireTime);
			$this->db->name('orders')->where('orderId',$orderId)->update(['orderStatus' => 5,'requireTime'=>"尽快送达(预计$requireTimeStr)"]);
			//订单日志
			$log = ["orderId"=>$orderId,"logContent"=>'配送员已接单',"logUserId"=>$shopId,"logType"=>0,"logTime"=>date('Y-m-d H:i:s',time())];
			$this->db->name('log_orders')->insert($log);
			ajaxReturn(array('status' => '1','msg' => '抢单成功'));
		}else{
			
			$user_delivery_config = db('system')->where(array('name' => 'delivery_user_config'))->find();
			$user_delivery_config = unserialize($user_delivery_config['value']);
			//###
			$data = db('send_order')->where(array('pay_status' => 1,'order_status' => 0,'id' => $orderId))->find();
			// 夜间配送费
			$extra_money = $data['extra_money'];
			// 配送员夜间配送提成
			$proportion = $data['proportion'];

			if (empty($data)) ajaxReturn(array('status' => '1','msg' => '该订单不存在'));
			$data['content'] = json_decode($data['content'],true);
			$order = [];
			if ($data['type'] == 3){
				$order['my_location'] = subMoney(getDistance($data['user_lat'], $data['user_lng'], $data['content']['buy_lat'], $data['content']['buy_lng']));
				$order['to_location'] = subMoney(getDistance($data['content']['buy_lat'], $data['content']['buy_lng'], $data['content']['get_lat'], $data['content']['get_lng']));
			}else{
				$order['my_location'] = subMoney(getDistance($data['user_lat'], $data['user_lng'], $data['content']['go_lat'], $data['content']['go_lng']));
				$order['to_location'] = subMoney(getDistance($data['content']['go_lat'], $data['content']['go_lng'], $data['content']['get_lat'], $data['content']['get_lng']));
			}
			foreach ($user_delivery_config as $k => $j){
				if ($j['go_distance'] >= $order['to_location']){
					switch ($data['content']['car']){
						case 1:
							$data['money'] = $j['go_shop_money'];
							break;
						case 2:
							$data['money'] = $j['go_shop_money2'];
							break;
						case 3:
							$data['money'] = $j['go_shop_money3'];
							break;
					}
					break;
				}
			}
			// 唐峰康改 添加配送单号
			$delivery_order_num = 'PS'. date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
			// 唐峰康改 如果存在夜间费用则计算夜间配送提成
			if ($extra_money > 0) {
				$data['money'] =$data['money'] + $extra_money * $proportion;
			}
			$insertData = ["userId"=>$userId,"orderId"=>$data['id'],"shopId"=>0,
					'user_send' => 1,"shopLngLat"=>'',"buyerLngLat"=>$data['user_lng'].','.$data['user_lat'],
					"status"=>0,"require_time"=>$data['send_time'],
					"deliverMoney"=>$data['money'],"time"=>time(),"delivery_order_num"=>$delivery_order_num,'diliverymanLngLat'=>$diliverymanLngLat];
			if (db('delivery_order')->insert($insertData)){
				db('send_order')->where(array('id' => $orderId))->setField('order_status',1);
				ajaxReturn(array('status' => '1','msg' => '抢单成功'));
			}
			
		}
		ajaxReturn(array('status' => '1','msg' => '抢单失败'));
	}



	// 确认收货，确认完成
	public function update_delivery_order(){
		if (!request()->isPost()) ajaxReturn(array('status' => 'error','msg' => '确认失败'));
		$token = $this->request->param('token');
		//$orderId = $this->request->post('orderId');
		$id = $this->request->post('orderId');
		$update_status = $this->request->post('status');
		if ($token != config('token')) ajaxReturn(array('status' => 'error','msg' => '确认失败'));
		$model = db('delivery_order');
		//$order = $model->where('orderId',$orderId)->find();
		$order = $model->where(array('id' => $id))->find();
		$orderId = $order['orderId'];
		
		if ($order['user_send'] != 1){
			$oto_model = $this->db->name('orders');
			$oto_order = $this->db->name('orders')->where('orderId',$orderId)->find();
			$oto_isRefund = $oto_order['isRefund'];

			if ($update_status == 0) {
				//要求送达时间
				$requireTime = $order['require_time'];
				// 判断订单是否取消
				if ($oto_isRefund == 1 || $oto_isRefund == 2 || $oto_isRefund == 3) {
					//$model->where('orderId',$orderId)->setField('iscancel',1);
					$model->where(array('id' => $id,'orderId' => $orderId))->setField('iscancel',1);
					ajaxReturn(array('status' => 2,'msg' => '由于您未开始配送，该笔订单费用无法获得。'));
				}elseif($oto_isRefund == '0'){
					// 由配送员确认订单状态：待取货-->配送中
					//$model->where('orderId',$orderId)->update(['status'=>1,'get_goods_time'=>time()]);
					$model->where(array('id' => $id,'orderId' => $orderId))->update(['status'=>1,'get_goods_time'=>time()]);
					$oto_model->where('orderId',$orderId)->update(['orderStatus' => 6,'pickup' => 1]);
					$shopId = $oto_model->where('orderId',$orderId)->value('shopId');
					// 订单日志
					$log = ["orderId"=>$orderId,"logContent"=>'配送员已取货',"logUserId"=>$shopId,"logType"=>0,"logTime"=>date('Y-m-d H:i:s',time())];
					$this->db->name('log_orders')->insert($log);
					ajaxReturn(array('status' => 'success','msg' => '确认成功'));
				}
	
			}elseif ($update_status == 1) {
				// 判断订单是否取消
				if ($oto_isRefund == 1 || $oto_isRefund == 2 || $oto_isRefund == 3) {
					// 订单取消时间
					$cancel_time = $order['cancel_time'];
					if ($cancel_time<=$order['require_time']) {
						$timeout = 1;
					}else{
						$timeout = 2;
					}
					$model->where(array('id' => $id,'orderId' => $orderId))->update(['iscancel'=>1,'timeout'=>$timeout]);
					ajaxReturn(array('status' => 2,'msg' => '由于您已开始配送，该笔订单费用正常获得。'));
				}elseif($oto_isRefund == 0){
					// 由配送员确认订单状态：配送中-->配送完成
					if (time()<=$order['require_time']) {
						$timeout = 1;
					}else{
						$timeout = 2;
					}
					$model->where(array('id' => $id,'orderId' => $orderId))->update(['status'=>2,'send_to_time'=>time(),'timeout'=>$timeout]);
					$oto_model->where('orderId',$orderId)->update(['orderStatus' => 7]);
					$shopId = $oto_model->where('orderId',$orderId)->value('shopId');
					// 订单日志
					$log = ["orderId"=>$orderId,"logContent"=>'配送员已送达',"logUserId"=>$shopId,"logType"=>0,"logTime"=>date('Y-m-d H:i:s',time())];
					$this->db->name('log_orders')->insert($log);
					ajaxReturn(array('status' => 'success','msg' => '确认成功'));
				}
			}
			
		}else{
			$orderInfo = db('send_order')->where(array('id' => $order['orderId']))->find();
			$orderInfo['content'] = json_decode($orderInfo['content']);
			$order['orderInfo'] = $orderInfo;
			$order_status = $orderInfo['order_status'];
			$pay_status = $orderInfo['pay_status'];
			if ($update_status == 0) {
				// 要求送达时间
				$requireTime = $order['require_time'];
				//判断订单是否取消
				if ($order_status == 5 || $pay_status == 2) {
					$model->where(array('id' => $id,'orderId' => $orderId))->setField('iscancel',1);
					ajaxReturn(array('status' => 2,'msg' => '由于您未开始配送，该笔订单费用无法获得。'));
				}else{
					// 由配送员确认订单状态：待取货-->配送中
					$model->where(array('id' => $id,'orderId' => $orderId))->update(['status'=>1,'get_goods_time'=>time()]);
					db('send_order')->where(array('id' => $orderInfo['id']))->setField('order_status',2);
					// 订单日志
// 					$log = ["orderId"=>$orderId,"logContent"=>'配送员已取货',"logUserId"=>$shopId,"logType"=>0,"logTime"=>date('Y-m-d H:i:s',time())];
// 					$this->db->name('log_orders')->insert($log);
					ajaxReturn(array('status' => 'success','msg' => '确认成功'));
				}
				
			}else if($update_status == 1){
				// 判断订单是否取消
				if ($order_status == 5 || $pay_status == 2) {
					// 订单取消时间
					$cancel_time = $order['cancel_time'];
					if ($cancel_time<=$order['require_time']) {
						$timeout = 1;
					}else{
						$timeout = 2;
					}
					$model->where(array('id' => $id,'orderId' => $orderId))->update(['iscancel'=>1,'timeout'=>$timeout]);
					db('send_order')->where(array('id' => $orderId))->update(array('pay_status' => 3,'order_status' => 5));
					
					$db_config = config('database.db_config');
					$db = \Think\Db::connect($db_config);
					if ($db->name('users')->where(array('userId' => $orderInfo['uid']))->setInc('userMoney',$orderInfo['money'])){
						//ajaxReturn(array('status' => 1,'msg' => '费用已退回余额中'));
						ajaxReturn(array('status' => 2,'msg' => '由于您已开始配送，该笔订单费用正常获得。'));
					}
					
					//ajaxReturn(array('status' => 2,'msg' => '由于您已开始配送，该笔订单费用正常获得。'));
				}else{
					// 由配送员确认订单状态：配送中-->配送完成
					if (time()<=$order['require_time']) {
						$timeout = 1;
					}else{
						$timeout = 2;
					}
					$model->where(array('id' => $id,'orderId' => $orderId))->update(['status'=>2,'send_to_time'=>time(),'timeout'=>$timeout]);
					// 原来的
					// db('send_order')->where(array('id' => $orderInfo['id']))->setField('order_status',3);
					// 唐峰康改  配送员确认配送完成只更改 is_delivery_confirm 为1 最终确认完成由客户确认或者自动确认
					db('send_order')->where(array('id' => $orderInfo['id']))->setField('is_delivery_confirm',1);
					// 订单日志
// 					$log = ["orderId"=>$orderId,"logContent"=>'配送员已送达',"logUserId"=>$shopId,"logType"=>0,"logTime"=>date('Y-m-d H:i:s',time())];
// 					$this->db->name('log_orders')->insert($log);
					ajaxReturn(array('status' => 'success','msg' => '确认成功'));
				}
			}
			
		}
		
		ajaxReturn(array('status' => 'error','msg' => '确认失败'));
	}

	// 唐峰康 更新配送员最新位置
	public function auto_update_location(){
		$user_id = $this->request->post('userId');
		$delivery_uid = _encrypt($user_id,'DECODE');
		$lng = $this->request->post('u_lng');
		$lat = $this->request->post('u_lat');
		$diliverymanLngLat = $lng.','.$lat;
		// $A = db('delivery_order')->where(array("userId"=>$delivery_uid))->setField('diliverymanLngLat', $diliverymanLngLat);
		// 必须是在配送中的状态
		$A = db('delivery_order')->where("userId = '{$delivery_uid}' and status = 0 or status =1")->setField('diliverymanLngLat', $diliverymanLngLat);
		if ($A !==false) {
			ajaxReturn(array('status' => '1','msg' => '更新成功'));
		}else{
			ajaxReturn(array('status' => '-1','msg' => '更新失败'));
		}

	}

	// 唐峰康改  用户超过4小时未确认配送完成则 自动确认
	public function auto_update_delivery_order(){
		// $this->post_check();
		// $this->is_validate();
		// 配送员id
		// 获取后台设置的自动确认收货时间
		$auto_recevie_time =  $this->db->name('sys_configs')->where(array('fieldCode'=>'automaticDelivery'))->value('fieldValue');
		if (!is_numeric($auto_recevie_time)) {
			$auto_recevie_time = 4;
		}
		$user_id = $this->request->post('userId');
		$delivery_uid = _encrypt($user_id,'DECODE');

		$lng = $this->request->post('u_lng');
		$lat = $this->request->post('u_lat');

		$rs = db('delivery_order')->where(array("userId"=>$delivery_uid))->select();
		
		foreach ($rs as $k => $v) {
			// 计算是否超过4个小时用户未确认到达
			if ($v['send_to_time'] == 0) {
				continue;
			}
			$hour=(time()-$v['send_to_time'])/3600; 

			if ($hour>=$auto_recevie_time) {
				if ($v['send_to_time']<=$v['require_time']) {
					$timeout = 1;
				}else{
					$timeout = 2;
				}

				db('delivery_order')->where(array('id' => $v['id']))->update(['status'=>3,'confirm_time'=>time(),'timeout'=>$timeout,'isAuto'=>1]);
				db('send_order')->where(array('id' => $v['orderId']))->update(array('order_status' => 3,'is_user_confirm' => 1,'is_delivery_confirm' => 1));
		
			}
		}


	}
	
	// 账单明细1
	public function f_get_bill(){
		$this->is_validate();
		$model = db('delivery_order');
		$user_id = $this->userinfo['id'];
		$up_time = $this->request->post('time'); //2017-9-1
		// $user_id = 14;
		// $up_time = '2017-8-28';
		// 一天开始（时间戳）
		$start_time = strtotime($up_time);
		// 一天结束（时间戳）
		$end_time = strtotime($up_time." +24 hours")-1;
		// 月初（时间）
		$start_month = date('Y-m',$start_time);
		// 月末（时间戳）
		$end_month = strtotime($start_month." +1 month")-1;
		// 月初（时间戳）
		$start_month = strtotime($start_month);

		$orders = $model->where('userId',$user_id)->where('time','between',[$start_time,$end_time])->order('id DESC')->select();
		if (count($orders)==0) {
			ajaxReturn(array('status' => 2));
		}
		$data = array();
		$status = 0;
		foreach ($orders as $order) {
			// 订单号
			$order_id = $order['orderId'];
			$id = $order['id'];
			// 配送完成时间
			$send_to_time = $order['send_to_time'];
			if ($send_to_time) {
				$send_to_time = date('Y-m-d H:i:s',$send_to_time);
			}else{
				$send_to_time = '未送达';
			}
			
			// 配送费
			$iscount = $order['iscount'];
			$money = subMoney($order['deliverMoney']);
			$money = round($money,2);
	
			// 状态
			$order_status = $order['status'];
			// 已到账订单
			if ($order_status==3) {
				$status = 3;
			}
			// 退单补偿
			elseif (($order_status==1 || $order_status==2) && $order['iscancel']==1) {
				$status = 2;
				
			}
			// 待到账
			elseif ($order_status==2 && $order['iscancel']==0) {
				$status = 1;
			}
			else{
				continue;
			}
			// p($order);
			$data[] = array("id"=>$id,"order_id"=>$order_id,"send_to_time"=>$send_to_time,"iscount"=>$iscount,"money"=>$money,"status"=>$status);
		}
		ajaxReturn(array('status' => 1, 'data' => $data));
	}
	// 账单明细2
	public function f_get_bill_m(){
		$this->is_validate();
		$model = db('delivery_order');
		$user_id = $this->userinfo['id'];
		$up_time = $this->request->post('time'); //2017-9-1
		// $user_id = 14;
		// $up_time = '2017-8-1';
		// 时间戳
		$up_time = strtotime($up_time);
		// 月初（时间）
		$start_month = date('Y-m',$up_time);
		// 月末（时间戳）
		$end_month = strtotime($start_month." +1 month")-1;
		// 月初（时间戳）
		$start_month = strtotime($start_month);

		$orders = $model->where(array('userId'=>$user_id,'iscount'=>1))->where('time','between',[$start_month,$end_month])->select();
		if (empty($orders)) {
			ajaxReturn(array('status' => 'error'));
		}
		$month_money = 0; // 月收入
		$order_num = 0;
		foreach ($orders as $order) {		
			$status = $order['status']; // 订单状态
			if ($status==3 || (($status==1 || $status==2) && $order['iscancel']==1)) {
				$month_money += $order['deliverMoney'];
				$order_num ++;
			}
		}
		$month_money = number_format($month_money,2,'.','');
		$data = array("money"=>$month_money,'num'=>$order_num);
		// 注册日期
		$reg_time = db('user')->where(array('id'=>$user_id))->value('time');
		$reg_time = date('Y-m-d',$reg_time);

		ajaxReturn(array('status' => 1,"reg_time"=>$reg_time,'data' => $data));
	}
	// 订单详情
	public function f_get_order_details(){

		$this->is_validate();
		$model = db('delivery_order');
		$userId = $this->userinfo['id'];
		//$orderId = $this->request->post('orderId');
		$id = $this->request->post('orderId');
		$data = array();
		// 订单
		$order = $model->where(array('userId'=>$userId,'id'=>$id))->find();
		$orderId = $order['orderId'];
		// 唐峰康改 其实都是用户发布的
		if ($order['user_send'] != 1){
			// 商家店铺id
			$shopId = $order['shopId'];
			// oto商家
			$oto_shop = $this->db->name('shops')->where('shopId',$shopId)->find();
			// oto订单
			$oto_order =  $this->db->name('orders')->where('orderId',$orderId)->find();
			// 订单状态
			$status = $order['status'];
			if (($status==0 || $status==1 || $status==2) && $order['iscancel']==1) {
				$status = 4; //用户取消订单
			}
			// 判断订单是否取消
			$oto_isRefund = $oto_order['isRefund'];
			if ($oto_isRefund == 1 || $oto_isRefund == 2 || $oto_isRefund == 3) {
				$status = 4; 	//用户取消订单
				$model->where('orderId',$orderId)->setField('iscancel',1);
			}
			// 配送费
			$iscount = $order['iscount'];
			// $deliverMoney = number_format($oto_order['deliverMoney'],2,'.','');
			$deliverMoney = $order['deliverMoney'];
			
			// 商家店铺名
			$shopName = $oto_shop['shopName'];
	
			// 商家地址
			$shopAddress = $oto_shop['shopAddress'];
	
			// 买家地址
			$buyerAddress = $oto_order['userAddress'];
	
			// 商家经纬度
			$shopLngLat = $order['shopLngLat'];
			$shopLngLatArr = explode(",", $shopLngLat);
	
			// 买家经纬度
			$buyerLngLat = $order['buyerLngLat'];
			$buyerLngLatArr = explode(",", $buyerLngLat);
	
			$shopLongitude = isset($shopLngLatArr[0]) ? $shopLngLatArr[0] : '';
			$shopLatitude = isset($shopLngLatArr[1]) ? $shopLngLatArr[1] : '';
			$buyerLongitude = isset($buyerLngLatArr[0]) ? $buyerLngLatArr[0] : '';
			$buyerLatitude = isset($buyerLngLatArr[1]) ? $buyerLngLatArr[1] : '';
			// 商家到买家的距离
			$shop_to_buyer = getDistance($shopLatitude,$shopLongitude,$buyerLatitude,$buyerLongitude);
			// 配送设置信息
			$delivery_config = delivery_config($shop_to_buyer);
	
			// 收货人
			$buyerName = $oto_order['userName'];
	
			// 买家留言
			if ($oto_order['orderRemarks']) {
				$orderRemarks = $oto_order['orderRemarks'];
			}else{
				$orderRemarks = '无';
			}
	
			// 商家电话
			$shopPhone = $oto_shop['shopTel'];
	
			// 买家电话
			$buyerPhone = $oto_order['userPhone'];
			// $buyerPhone = $oto_order['userTel'];
	
			// 商品信息
			// oto订单商品
			$oto_order_goods =  $this->db->name('order_goods')->where('orderId',$orderId)->select();
			$goodsData = array();
			foreach ($oto_order_goods as $order_goods) {
				// 商品id
				$goodsId = $order_goods['goodsId'];
				// 商品name
				$goodsNmae = $order_goods['goodsName'];
				// 商品数量
				$goodsNums = $order_goods['goodsNums'];
				// oto商品
				// $oto_goods = $this->db->name('goods')->where(array('goodsId'=>$goodsId,'shopId'=>$shopId))->find();
				// 商品价格
				$goodsPrice = $order_goods['goodsPrice'];
				// 商品总价
				$goodsAllPrice = $goodsNums * $goodsPrice;
	
				$goodsData[] = array("goodsNmae"=>$goodsNmae,"goodsNums"=>$goodsNums,"goodsAllPrice"=>$goodsAllPrice);
	
			}
	
			// 优惠
			$couponData = array();
			if ($oto_order['couponId']) {
				$coupon = $this->db->name('youhui')->where(array('id'=>$oto_order['couponId'],'supplier_id'=>$shopId))->find();
				if (!empty($coupon)){
					$couponData['status'] = 1; //使用优惠券
					$couponData['name'] = $coupon['name'];
					$couponData['money'] = number_format(abs($oto_order['couponMoney']),2,'.','');
				}else{
					$couponData['status'] = 0; //没有使用优惠券
				}
			}else{
				$couponData['status'] = 0; //没有使用优惠券
			}
	
			// 配送信息
			// 接单时间（时间戳）
			$time = $order['time'];
	
			// 买家下单时间（时间戳）
			$createTime = strtotime($oto_order['createTime']);
	
			// 要求送达时间（时间戳）
			// $requireTime = $oto_order['requireTime'];
			$requireTime = $order['require_time'];
			// 要求配送时长
			$has_time = $delivery_config['go_distance_time']*60;
	
			// 送达时间（时间戳）
			$sendToTime = $order['send_to_time'];
	
			// 订单取消时间（时间戳）
			if ($status == 4) $cancel_time = $order['cancel_time'];
			// $cancel_time = $time + 3000;
	
			// 已配送时长/配送时长
			if ($status == 0 || $status == 1){ 		// 配送中
				$used_time = time() - $time;		// 配送中(已配送时长)(时间戳)
			}elseif ($status == 2 || $status == 3){
				$used_time = $sendToTime - $time;	// 订单完成(配送时长)(时间戳)
				
			}elseif ($status == 4) {
				$used_time = $cancel_time - $time;	// 订单取消(配送时长)(时间戳)
				
			}else {
				$used_time = 0;
			}

			// 配送倒计时
			$countdown = array();
			if ($has_time>=$used_time) {
				$countdown["status"] = 1;	//没有超时
				$countdown["time"] = round(abs($requireTime - time())/60);
				if ($status == 2 || $status == 3 || $status == 4){
					$countdown["time"] = '无';
				}
			}else{
				$countdown["status"] = 0;	//超时
				if ($status == 2 || $status == 3){
					$countdown["time"] = round(($sendToTime - $requireTime)/60);
				}else if ($status == 4) {
					$countdown["time"] = round(($cancel_time - $requireTime)/60);
				}else{
					$countdown["time"] = round(abs(time() - $requireTime)/60);
				}
			}
			if ($status == 4) $cancel_time = date('Y-m-d H:i:s',$cancel_time); // 取消时间（标准时间）
			$data['id'] = $order['id'];
			$data['orderId'] = $oto_order['orderNo'];
			$data['countdown'] = $countdown; 		// 配送倒计时
			$data['status'] = $status;
			$data['iscount'] = $iscount;
			$data['deliverMoney'] = $deliverMoney;
			$data['shopName'] = $shopName;
			$data['shopAddress'] = $shopAddress;
			$data['shopLngLat'] = $shopLngLat;
			$data['buyerAddress'] = $buyerAddress;
			$data['buyerLngLat'] = $buyerLngLat;
			$data['shop_to_buyer'] = $shop_to_buyer;
			$data['buyerName'] = $buyerName;
			$data['orderRemarks'] = $orderRemarks;
			$data['shopPhone'] = $shopPhone;
			$data['buyerPhone'] = $buyerPhone;
			$data['goodsData'] = $goodsData;
			$data['couponData'] = $couponData;
			$data['time'] = date('Y-m-d H:i:s',$time); 					// 接单时间
			$data['requireTime'] = date('Y-m-d H:i:s',$requireTime);	// 要求送达时间
			$data['used_time'] = round($used_time/60);		// 配送时长（已配送时长）
			$data['sendToTime'] = date('Y-m-d H:i:s',$sendToTime);		// 送达时间
			$data['order_type'] = 'default';
			ajaxReturn(array('status' => 'success','data' => $data));
		}else{
			$user_sendOrder = db('send_order')->where(array('id' => $order['orderId']))->find();
			$user_sendOrder['content'] = json_decode($user_sendOrder['content'],true);
			$lng = $this->request->post('u_lng');
			$lat = $this->request->post('u_lat');
			switch ($user_sendOrder['content']['urgent']){
				case 1:
					$user_sendOrder['content']['urgent_text'] = '正常配送';
					break;
				case 2:
					$user_sendOrder['content']['urgent_text'] = '加急配送';
					break;
			}
			switch ($user_sendOrder['content']['car']){
				case 1:
					$user_sendOrder['content']['car_text'] = '摩托车(电动车)';
					break;
				case 2:
					$user_sendOrder['content']['car_text'] = '小汽车';
					break;
				case 3:
					$user_sendOrder['content']['car_text'] = '火车';
					break;
			}
			switch ($user_sendOrder['content']['type']){
				case 1:
					$user_sendOrder['content']['type_text'] = '帮我送';
					break;
				case 2:
					$user_sendOrder['content']['type_text'] = '帮我取';
					break;
				case 3:
					$user_sendOrder['content']['type_text'] = '帮我买';
					break;
				case 4:
					$user_sendOrder['content']['type_text'] = '饿了么订单';
					break;
			}
			$user_sendOrder['content']['money'] = $user_sendOrder['money'];
			$user_sendOrder['content']['pay_status'] = $user_sendOrder['pay_status'];
			$user_sendOrder['content']['order_status'] = $user_sendOrder['order_status'];

			/** add by hfc 5.14 高德转百度*/
			// $lngAndLat = $this->doGet($user_sendOrder['user_lat'],$user_sendOrder['user_lng']);
			// // ajaxReturn(array('status' => 'success','data' => $lngAndLat));
			// $user_sendOrder['user_lng'] = $lngAndLat['lng'];
			// $user_sendOrder['user_lat'] = $lngAndLat['lat'];
			/** add end */


			$user_sendOrder['content']['user_lng'] = $user_sendOrder['user_lng'];
			$user_sendOrder['content']['user_lat'] = $user_sendOrder['user_lat'];
			$order['content'] = $user_sendOrder['content'];

			/** add by hfc 5.14 高德转百度*/
			// $lngAndLat = $this->doGet($user_sendOrder['content']['get_lat'],$user_sendOrder['content']['get_lng']);
			// $user_sendOrder['content']['get_lng'] = $lngAndLat['lng'];
			// $user_sendOrder['content']['get_lat'] = $lngAndLat['lat'];
			/** add end */
			
			if ($user_sendOrder['type'] == 3){
				/** add by hfc 5.14 高德转百度*/
				// $lngAndLat = $this->doGet($user_sendOrder['content']['buy_lat'],$user_sendOrder['content']['buy_lng']);
				// $user_sendOrder['content']['buy_lng'] = $lngAndLat['lng'];
				// $user_sendOrder['content']['buy_lat'] = $lngAndLat['lat'];
				/** add end */
				$order['my_location'] = subMoney(getDistance($lat, $lng, $user_sendOrder['content']['buy_lat'], $user_sendOrder['content']['buy_lng']));
				$order['to_location'] = subMoney(getDistance($user_sendOrder['content']['buy_lat'], $user_sendOrder['content']['buy_lng'], $user_sendOrder['content']['get_lat'], $user_sendOrder['content']['get_lng']));
			}else{
				/** add by hfc 5.14 高德转百度*/
				// $lngAndLat = $this->doGet($user_sendOrder['content']['go_lat'],$user_sendOrder['content']['go_lng']);
				// $user_sendOrder['content']['go_lng'] = $lngAndLat['lng'];
				// $user_sendOrder['content']['go_lat'] = $lngAndLat['lat'];
				/** add end */
				$order['my_location'] = subMoney(getDistance($lat, $lng, $user_sendOrder['content']['go_lat'], $user_sendOrder['content']['go_lng']));
				$order['to_location'] = subMoney(getDistance($user_sendOrder['content']['go_lat'], $user_sendOrder['content']['go_lng'], $user_sendOrder['content']['get_lat'], $user_sendOrder['content']['get_lng']));
			}
			$iscount = $order['iscount'];
			//配送设置信息
			$delivery_config = delivery_user_config($order['to_location']);
			// 订单状态
			$status = $order['status'];
			if (($status==0 || $status==1 || $status==2) && $order['iscancel']==1) {
				$status = 4; 	//用户取消订单
			}
			// 判断订单是否取消
			if ($user_sendOrder['order_status'] == 5 || $user_sendOrder['pay_status'] != 1) {
				$status = 4; 	//用户取消订单
				$model->where(array('userId' => $userId,'id' => $order['id']))->setField('iscancel',1);
			}
			

			// 配送信息
			// 接单时间（时间戳）
			$time = $order['time'];
			
			//买家下单时间（时间戳）
			$createTime = strtotime($user_sendOrder['time']);
			
			// 要求送达时间（时间戳）
			// $requireTime = $oto_order['requireTime'];
			$requireTime = $order['require_time'];
			// 要求配送时长
			$has_time = $delivery_config['go_distance_time']*60;
			
			// 送达时间（时间戳）
			$sendToTime = $order['send_to_time'];
			
			// 订单取消时间（时间戳）
			if ($status == 4) $cancel_time = $order['cancel_time'];
			// $cancel_time = $time + 3000;
			
			// 已配送时长/配送时长
			// 0 待取货 1 配送中
			if ($status == 0 || $status == 1){ 		// 配送中
				$used_time = time() - $time;		// 配送中(已配送时长)(时间戳)
			}
			// 2配送员确认送达 3 客户确认
			elseif ($status == 2 || $status == 3){
				$used_time = $sendToTime - $time;	// 订单完成(配送时长)(时间戳)
				
			}elseif ($status == 4) {
				$used_time = $cancel_time - $time;	// 订单取消(配送时长)(时间戳)
				
			}else {
				$used_time = 0;
			}

			if ($order['cancel_time'] !=0) {
				$used_time = $order['cancel_time']- $order['time'];
			}
	

			
			// 配送倒计时
			$countdown = array();
			if ($has_time>=$used_time) {
				$countdown["status"] = 1;	//没有超时
				$countdown["time"] = round(abs($requireTime - time())/60);
				if ($status == 2 || $status == 3 || $status == 4){
					$countdown["time"] = '无';
				}
			}else{
				$countdown["status"] = 0;	//超时
				if ($status == 2 || $status == 3){
					$countdown["time"] = round(($sendToTime - $requireTime)/60);
				}else if ($status == 4) {
					$countdown["time"] = round(($cancel_time - $requireTime)/60);
				}else{
					$countdown["time"] = round(abs(time() - $requireTime)/60);
				}
			}

			if ($status == 4) $cancel_time = date('Y-m-d H:i:s',$cancel_time); // 取消时间（标准时间）

			if ($user_sendOrder['type'] == 3){
				$order['shopLngLat'] = $user_sendOrder['content']['buy_lng'].','.$user_sendOrder['content']['buy_lat'];
				$order['shopAddress'] = $user_sendOrder['content']['buy_address'].$user_sendOrder['content']['buy_number'];
			}else{
			
				$order['shopAddress'] = $user_sendOrder['content']['go_address'].$user_sendOrder['content']['go_number'];
				$order['shopLngLat'] = $user_sendOrder['content']['go_lng'].','.$user_sendOrder['content']['go_lat'];
			}

			$order['buyerLngLat'] = $user_sendOrder['content']['get_lng'].','.$user_sendOrder['content']['get_lat'];
			$order['shop_to_buyer'] = $order['to_location'];
			$order['buyerAddress'] = $user_sendOrder['content']['get_address'].$user_sendOrder['content']['get_number'];
			$order['countdown'] = $countdown; 		// 配送倒计时
			$order['status'] = $status;
			$order['iscount'] = $iscount;
			$order['countdown'] = $countdown; 		// 配送倒计时
			$order['status'] = $status;
			$order['time'] = date('Y-m-d H:i:s',$time); 					// 接单时间
			$order['requireTime'] = date('Y-m-d H:i:s',$requireTime);	// 要求送达时间
			$order['used_time'] = round($used_time/60);		// 配送时长（已配送时长）
			$order['sendToTime'] = date('Y-m-d H:i:s',$sendToTime);		// 送达时间
			$order['order_type'] = 'user_send';

			// 唐峰康改 
			// 平台订单号
			$order['send_order_num'] =$user_sendOrder['send_order_num'];
			// 配送订单号
			$order['delivery_order_num'] =$order['delivery_order_num'];
			
			// 唐峰康改
			$db_config = config('database.db_config');
			$db = \Think\Db::connect($db_config);
			$users = $db->name('users')->where(array('userId' => $user_sendOrder['uid']))->find();
			$order['user_face'] = $users['userPhoto'];
			if ($order['ishidden']){
				$order['username'] = '匿名：***';
			}else{
				$order['username'] = $users['userName'] ? $users['userName'] : str_replace(mb_substr($users['userPhone'], 3,5,'utf-8'), '*****', $users['userPhone']);
			}

			// 唐峰康改
			// 判断是否是 不结算配送费
			if ($order['iscount'] == 2) {
				// 获取不配送原因
				// 后台不结算配送费的时候的消息信息
				$reasonInfo = db('user_msg')->where(array('orderid'=>$order['id']))->find();
				$issueInfo = db('issue')->where(array('id'=>$reasonInfo['type']))->find();
				$serviceInfo =  $db->name('sys_configs')->where(array('fieldCode'=>'phoneNo'))->find();
				$msg =  $issueInfo['title'] ;
				if ($reasonInfo['content']) {
					$msg =  $issueInfo['title'].'('.$reasonInfo['content'].')';
				}
				$reason_msg ='由于'.'“'.$msg.'“'.'，所以您不能获得本次配送费，如有疑问，请联系客服：';
				$order['reason_msg'] = $reason_msg;
				$order['service_tel'] = $serviceInfo['fieldValue'];
			}
			ajaxReturn(array('status' => 'success','data' => $order));
		}
	}

	/** add by hfc 5.14 */
	//高德坐标转百度坐标
    private function gcjBd($lat,$lng)
    {
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $pi = 3.14159265358979324; // 圆周率
        $a = 6378245.0; // WGS 长轴半径
        $ee = 0.00669342162296594323; // WGS 偏心率的平方
        $x = $lat;
        $y = $lng;
        $z = sqrt($x * $x + $y * $y) + 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) + 0.000003 * cos($x * $x_pi);
        $bd_x = $z * cos($theta) + 0.0065;
        $bd_y = $z * sin($theta) + 0.006;
        $data['lat'] = $bd_x;
        $data['lng'] = $bd_y;
        return $data;
    }

    /**
     * add by hfc 5.15 
     * @param string $url
     * @return mixed
     */
    public function doGet($lat,$lng)
    {
    	$url = "http://api.map.baidu.com/geoconv/v1/?coords=".$lng.",".$lat."&from=3&to=5&ak=".$this->ak;
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
       	$arr = json_decode($output,true);
       	if($arr['status']==0){
       		$data['lat'] = $arr['result'][0]['y'];
       		$data['lng'] = $arr['result'][0]['x'];
       	}else{
       		$data['lat'] = $lat;
       		$data['lng'] = $lng;
       	}
        return $data;
    }


	// /** 
 //     * 求两个已知经纬度之间的距离,单位为km 
 //     * @param lng1,lng2 经度 
 //     * @param lat1,lat2 纬度 
 //     * @return float 距离，单位为km 
 //     **/  
 //    public static function getTwoClockDistance($lat1,$lng1,$lat2,$lng2){  
 //        //将角度转为狐度  
 //        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度  
 //        $radLat2 = deg2rad($lat2);  
 //        $radLng1 = deg2rad($lng1);  
 //        $radLng2 = deg2rad($lng2);  
 //        $a = $radLat1 - $radLat2;  
 //        $b = $radLng1 - $radLng2;  
 //        $s = 2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6371;  
 //        return round($s,1);  
 //    }  
}

?>